<?php

namespace Modules\Shop\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Category;
use Modules\Shop\Http\Requests\CategoryRequest;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $category = Category::category_cate();
//        dd($category);
        return view('shop::category.index',compact('category'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('shop::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $post = $request->all();
        Category::create($post);
        session()->flash('success','添加成功');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('shop::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
//        获取当前ID对应的旧数据
        $category = Category::find($id);
        $categorys =Category::getTreeCategory($category);
        return view('shop::category.edit',compact('category','categorys'));
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(CategoryRequest $request,$id)
    {
        $category = Category::find($id);
        $post = $request->all();
        $category->cname=$post['cname'];
        $category->pid = $post['pid'];
        $category->save();
        session()->flash('success','修改成功');
        return redirect()->route('category.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        $category = Category::find($id);
        if(Category::hasChildCategory($category)){
            //为真就是有子集不能删除
            session()->flash('danger','请先删除当前分类的子分类,再来删除该分类');
            return back();
        }
        Category::destroy($id);
        session()->flash('success','删除成功');
        return redirect()->route('category.index');
    }
}
